// delegateshimobject.cpp : Implementation of Cdelegateshimobject

#include "stdafx.h"
#include "delegateshimobject.h"


// Cdelegateshimobject


STDMETHODIMP Cdelegateshimobject::createdelegateableobject(BSTR ObjectProgID, BSTR SPN, BSTR ServerName,VARIANT* object)
{
	HRESULT hr = S_OK;

	VARIANT* tempvar = new VARIANT;
	VariantInit(tempvar);
	

	MULTI_QI mqi = {&IID_IUnknown, 0, 0}; 
	COAUTHINFO cai = {
		RPC_C_AUTHN_GSS_KERBEROS,	// AuthType 
		RPC_C_AUTHZ_DEFAULT,		// 
		SPN,						// 1.FQDN of the server system, like this: L"rpcss/server1.domain.com" 
		RPC_C_AUTHN_LEVEL_PKT,		// RPC_C_AUTHN_LEVEL_CONNECT,
		RPC_C_IMP_LEVEL_DELEGATE,	// RPC_C_IMP_LEVEL_IMPERSONATE, 
		NULL, 
		RPC_C_QOS_CAPABILITIES_MUTUAL_AUTH  //EOAC_NON
	}; 

	COSERVERINFO csi = {NULL, ServerName /*L"server1"*/, &cai, NULL};	// 2.Name of the server system
	CLSID clsid;
	hr = CLSIDFromProgID(ObjectProgID /*L"TestProj.test"*/, &clsid);	// 3.Prog Id of the component
	hr = CoCreateInstanceEx(clsid, NULL, CLSCTX_REMOTE_SERVER, &csi, 1, &mqi);

	if SUCCEEDED(hr){
		if SUCCEEDED(mqi.hr){
			tempvar->vt = VT_DISPATCH;
			hr = mqi.pItf->QueryInterface(IID_IDispatch, (LPVOID*)&tempvar->pdispVal);
			object->vt = tempvar->vt;		// copy the type and dispVal.
			object->pdispVal = tempvar->pdispVal;
			object->pdispVal->AddRef();		// Keep it around 
			mqi.pItf->Release();			// Release the activated interface
		}
		else hr = mqi.hr;
	}
	VariantClear(tempvar);		// this does a pdispVal->Release()
	delete tempvar;				// clean up the temporary Variant
	return hr;
}
